<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Admin;
use App\Models\AdminGroup;
use Illuminate\Http\Request;
use Validator;

class AdminController extends Controller{
	
	public function getIndex(){
		$data = Admin::orderBy('admin_id')->with('hasOneAdminGroup')->paginate(15);
		view()->share("data", $data);
		return view('Admin.Admin.index');
	}
	
	public function getAdd(){
		$data['group'] = AdminGroup::orderBy('group_id')->get()->toJson();
		view()->share("data", $data);
		return view('Admin.Admin.add');
	}
	
	public function getEdit(Request $request){
		$getData = $request->only('id');
		$map['admin_id'] = $getData['id'];
		$data['admin'] = Admin::where($map)->first()->toJson();
		$data['group'] = AdminGroup::orderBy('group_id')->get()->toJson();
		view()->share("data", $data);
		return view('Admin.Admin.add');
	}
	
	public function postHandle(Request $request){
		$postData = $request->all();
		
		if(empty($postData['admin_id'])){   //新增
			
			$rules = [                      //规则
				'group_id' => 'required',
				'username' => 'required',
				'password' => 'required'
			];
			$messages = [                   //验证失败时的错误消息
				'group_id.required' => '请选择权限组！',
				'username.required' => '用户名不能为空！',
				'password.required' => '密码不能为空！'
			];
			$validation = Validator::make($postData, $rules, $messages);  //执行验证
			
			if($validation->fails()){   //判断验证是否成功
				return retArray(404, $validation->errors()->first());    //返回验证错误信息
			}
			if($postData['group_id'] == "undefined"){
				return retArray(404, '请选择权限组！');
			}
			$data['group_id'] = $postData['group_id'];
			$data['username'] = $postData['username'];
			$data['password'] = md5($postData['password']);
			
			
			$ret = Admin::insert($data);
			if($ret === true){
				return retArray(200, "添加成功！");
			}else{
				return retArray(404, "添加失败！");
			}
		}else{                              //修改
			
			$rules = [                      //规则
				'group_id' => 'required',
				'username' => 'required',
			];
			$messages = [                   //验证失败时的错误消息
				'group_id.required' => '请选择权限组！',
				'username.required' => '用户名不能为空！',
			];
			$validation = Validator::make($postData, $rules, $messages);  //执行验证
			
			if($validation->fails()){   //判断验证是否成功
				return retArray(404, $validation->errors()->first());    //返回验证错误信息
			}
			$data['group_id'] = $postData['group_id'];
			$data['username'] = $postData['username'];
			if(!empty($postData['password'])){
				$data['password'] = md5($postData['password']);
			}
			
			$ret = Admin::where(["admin_id" => $postData['admin_id']])->update($data);
			if($ret === 1){
				return retArray(200, "修改成功！");
			}else{
				return retArray(404, "修改失败！");
			}
		}
	}
	
	public function getDel(Request $request){
		$getData = $request->only('id');
		$ret = Admin::destroy($getData['id']);
		if($ret === 1){
			return retArray(200, "删除成功！");
		}else{
			return retArray(404, "删除失败！");
		}
	}
	
	
}